package com.cherry.example.network.tcp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/*
需求： 实现客户端与服务端一问一答聊天。
*/

//聊天客户端
public class Demo2Client {
	
	public static void main(String[] args) throws IOException {
		//第一步：建立tcp客户端的服务
		Socket socket = new Socket(InetAddress.getLocalHost(),9090);
		//第二步： 准备好数据
		BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
		//获取socket的输出流对象
		OutputStreamWriter socketOut = new OutputStreamWriter(socket.getOutputStream());
		//获取socket的输入流
		BufferedReader socketIn = 	new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		
		String line = null;
		while((line  = keyReader.readLine())!=null){
			socketOut.write(line+"\r\n");
			socketOut.flush();
			//读取服务端反馈会的数据
			line = socketIn.readLine();
			System.out.println("客户端接收到："+ line);
			
			
		}		
		
		//关闭资源
		socket.close();
	}
}
